using AntdUI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TangLiveRecorder.Models;
using static TangLiveRecorder.Data;

namespace TangLiveRecorder.Controls
{
    public partial class FileControl : UserControl, ITransient
    {
        private Form _form;
        // 移除选择相关变量

        public FileControl(MainWindow form)
        {
            InitializeComponent();
            this.Tag = "File";
            this.Dock = DockStyle.Fill;
            this.panelFileList.Gap = 15;
            LoadData();
            _form = form;

            // 订阅文件事件
            FileAdded += OnFileAdded;
            FileRemoved += OnFileRemoved;
            FilesCleared += OnFilesCleared;
        }

        private void LoadData()
        {
            panelFileList.Items.Clear();
            foreach (var item in Data.files)
            {
                AntdUI.VirtualItem virtualItem = new VItem(new IFile(item));
                panelFileList.Items.Add(virtualItem);
            }
        }

        private void OnFileAdded(object sender, FileEventArgs e)
        {
            var virtualItem = new VItem(new IFile(e.File));
            panelFileList.Items.Add(virtualItem);
        }

        private void OnFileRemoved(object sender, FileEventArgs e)
        {
            var itemToRemove = panelFileList.Items.OfType<VItem>()
                .FirstOrDefault(item => item.data.Guid == e.File.Guid);
            if (itemToRemove != null)
            {
                panelFileList.Items.Remove(itemToRemove);
            }
        }

        private void OnFilesCleared(object sender, EventArgs e)
        {
            panelFileList.Items.Clear();
        }

        private void btnClearFiles_Click(object sender, EventArgs e)
        {
            if (Data.files.Count == 0)
            {
                AntdUI.Message.warn(_form, "文件列表已为空", autoClose: 2);
                return;
            }

            AntdUI.Modal.open(new AntdUI.Modal.Config(_form, "确认清空", "确定要清空所有文件吗？")
            {
                Icon = AntdUI.TType.Warn,
                OkText = "确定",
                CancelText = "取消",
                OnOk = (Config) =>
                {
                    ClearFiles();
                    return true;
                }
            });
        }

        // 移除全选功能

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            if (disposing)
            {
                // 取消订阅事件
                FileAdded -= OnFileAdded;
                FileRemoved -= OnFileRemoved;
                FilesCleared -= OnFilesCleared;

                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private class IFile : Models.FileInfos
        {
            public IFile()
            { }

            public IFile(Models.FileInfos item)
            {
                this.Guid = item.Guid;
                this.Name = item.Name;
                this.Path = item.Path;
                this.Size = item.Size;
                this.CreatedTime = item.CreatedTime;
                this.ModifiedTime = item.ModifiedTime;
                this.Description = item.Description;
            }
        }

        private class VItem : AntdUI.VirtualShadowItem
        {
            public IFile data;

            public VItem(IFile d)
            {
                data = d;
            }

            private StringFormat s_f = AntdUI.Helper.SF(lr: StringAlignment.Near);
            private StringFormat s_f_wrap = AntdUI.Helper.SF(lr: StringAlignment.Near, tb: StringAlignment.Near);

            public override void Paint(AntdUI.Canvas g, AntdUI.VirtualPanelArgs e)
            {
                // 绘制背景和边框
                var bgColor = data.Exists ? AntdUI.Style.Db.BgBase : Color.FromArgb(250, 240, 240);
                using (var brush = new SolidBrush(bgColor))
                {
                    using (var path = AntdUI.Helper.RoundPath(e.Rect, e.Radius))
                    {
                        g.Fill(brush, path);
                        var borderColor = Hover ? AntdUI.Style.Db.BorderColorDisable : AntdUI.Style.Db.BorderColor;
                        using (var brush_bor = new Pen(borderColor, thickness))
                        {
                            g.Draw(brush_bor, path);
                        }
                    }
                }

                // 如果文件不存在，添加半透明遮罩
                if (!data.Exists)
                {
                    using (var brush = new SolidBrush(Color.FromArgb(128, 255, 255, 255)))
                    {
                        using (var path = AntdUI.Helper.RoundPath(e.Rect, e.Radius))
                        {
                            g.Fill(brush, path);
                        }
                    }
                }

                // 移除选择框绘制逻辑

                // 绘制删除按钮
                deleteButtonRect = new Rectangle(e.Rect.X + e.Rect.Width - delete_button_size - size, e.Rect.Y + size, delete_button_size, delete_button_size);
                using (var brush = new SolidBrush(Color.FromArgb(255, 77, 79)))
                {
                    using (var path = AntdUI.Helper.RoundPath(deleteButtonRect, delete_button_size / 2))
                    {
                        g.Fill(brush, path);
                    }
                }

                // 绘制删除按钮的 X 符号
                using (var pen = new Pen(Color.White, 2))
                {
                    int margin = 4;
                    g.DrawLine(pen,
                        deleteButtonRect.X + margin, deleteButtonRect.Y + margin,
                        deleteButtonRect.X + deleteButtonRect.Width - margin, deleteButtonRect.Y + deleteButtonRect.Height - margin);
                    g.DrawLine(pen,
                        deleteButtonRect.X + deleteButtonRect.Width - margin, deleteButtonRect.Y + margin,
                        deleteButtonRect.X + margin, deleteButtonRect.Y + deleteButtonRect.Height - margin);
                }

                int currentY = e.Rect.Y + size;

                // 第一行：文件图标 + 文件类型
                var fileIconRect = new Rectangle(e.Rect.X + size, currentY, file_icon_size, file_icon_size);

                // 绘制文件图标
                var iconColor = data.Exists ? AntdUI.Style.Db.Primary : Color.FromArgb(190, 190, 190);
                var iconBitmap = AntdUI.SvgExtend.SvgToBmp(data.FileIcon, file_icon_size, file_icon_size, iconColor);
                if (iconBitmap != null)
                {
                    g.Image(iconBitmap, fileIconRect);
                }
                else
                {
                    using (var brush = new SolidBrush(iconColor))
                    {
                        using (var path = AntdUI.Helper.RoundPath(fileIconRect, 4))
                        {
                            g.Fill(brush, path);
                        }
                    }
                }

                var textColor = data.Exists ? AntdUI.Style.Db.Text : Color.FromArgb(140, 140, 140);
                using (var fore = new SolidBrush(textColor))
                {
                    using (var font_type = new Font(e.Panel.Font.FontFamily, 10F, FontStyle.Bold))
                    {
                        var typeRect = new Rectangle(e.Rect.X + size + file_icon_size + size, currentY,
                            e.Rect.Width - size - file_icon_size - size - delete_button_size - size2, line_height);
                        g.String(data.FileType, font_type, fore, typeRect, s_f);
                    }
                }

                currentY += line_height + size;

                // 分割线
                using (var brush = new SolidBrush(AntdUI.Style.Db.Split))
                {
                    g.Fill(brush, new RectangleF(e.Rect.X + size, currentY - thickness / 2F,
                        e.Rect.Width - size2, thickness));
                }

                currentY += size;

                // 第二行：文件名
                using (var fore = new SolidBrush(textColor))
                {
                    using (var font_name = new Font(e.Panel.Font.FontFamily, 11F, FontStyle.Bold))
                    {
                        var nameRect = new Rectangle(e.Rect.X + size, currentY,
                            e.Rect.Width - size - delete_button_size - size2, line_height);
                        g.String(data.Name, font_name, fore, nameRect, s_f);
                    }
                }

                currentY += line_height + size;

                // 第三行：文件大小 + 修改时间
                var descColor = data.Exists ? AntdUI.Style.Db.TextSecondary : Color.FromArgb(160, 160, 160);
                using (var fore = new SolidBrush(descColor))
                {
                    using (var font_desc = new Font(e.Panel.Font.FontFamily, 9F))
                    {
                        var infoText = $"{data.SizeFormatted} • {data.ModifiedTime:yyyy-MM-dd HH:mm}";
                        var infoRect = new Rectangle(e.Rect.X + size, currentY,
                            e.Rect.Width - size - delete_button_size - size2, line_height);
                        g.String(infoText, font_desc, fore, infoRect, s_f);
                    }
                }

                currentY += line_height + size;

                // 第四行：文件路径
                Color pathColor;
                if (isPathHover)
                {
                    pathColor = data.Exists ? AntdUI.Style.Db.Primary : Color.FromArgb(100, 149, 237);
                }
                else
                {
                    pathColor = data.Exists ? AntdUI.Style.Db.TextTertiary : Color.FromArgb(180, 180, 180);
                }

                using (var fore = new SolidBrush(pathColor))
                {
                    using (var font_path = new Font(e.Panel.Font.FontFamily, 8F, isPathHover ? FontStyle.Underline : FontStyle.Regular))
                    {
                        pathRect = new Rectangle(e.Rect.X + size, currentY,
                            e.Rect.Width - size - delete_button_size - size2, line_height);
                        g.String(data.Path, font_path, fore, pathRect, s_f);
                    }
                }
            }

            private int thickness = 1, size = 10, size2 = 20;
            private int file_icon_size = 20, line_height = 24, delete_button_size = 20;

            private Rectangle deleteButtonRect;
            private Rectangle pathRect;
            private bool isPathHover = false;

            public override Size Size(AntdUI.Canvas g, AntdUI.VirtualPanelArgs e)
            {
                var dpi = AntdUI.Config.Dpi;
                thickness = (int)(1 * dpi);
                size = (int)(10 * dpi);
                size2 = size * 2;
                file_icon_size = (int)(20 * dpi);
                line_height = (int)(24 * dpi);
                delete_button_size = (int)(20 * dpi);

                // 计算总高度：上边距 + 文件类型行 + 间距 + 分割线间距 + 文件名行 + 间距 + 信息行 + 间距 + 路径行 + 下边距
                int totalHeight = size + line_height + size + size + line_height + size + line_height + size + line_height + size;
                return new Size((int)(300 * dpi), totalHeight);
            }

            public override void MouseClick(VirtualPanel sender, VirtualPanelMouseArgs e)
            {
                // 检查是否点击了删除按钮
                if (deleteButtonRect.Contains(e.Location))
                {
                    AntdUI.Modal.open(new AntdUI.Modal.Config(sender.FindForm(), "确认删除", "确定要从列表中移除这个文件吗？")
                    {
                        Icon = AntdUI.TType.Warn,
                        OkText = "确定",
                        CancelText = "取消",
                        OnOk = (Config) =>
                        {
                            RemoveFile(data.Guid);
                            return true;
                        }
                    });
                    return;
                }

                // 移除选择框点击处理

                // 检查是否点击了路径
                if (pathRect.Contains(e.Location))
                {
                    try
                    {
                        if (data.Exists)
                        {
                            // 在资源管理器中显示文件
                            System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{data.Path}\"");
                        }
                        else
                        {
                            AntdUI.Message.warn(sender.FindForm(), "文件不存在", autoClose: 2);
                        }
                    }
                    catch
                    {
                        AntdUI.Message.error(sender.FindForm(), "无法打开文件位置", autoClose: 2);
                    }
                    return;
                }

                base.MouseClick(sender, e);
            }

            public override void MouseLeave(VirtualPanel sender, VirtualPanelMouseArgs e)
            {
                if (Hover)
                {
                    SetHover(false);
                    sender.Invalidate();
                }

                if (isPathHover)
                {
                    isPathHover = false;
                    sender.Invalidate();
                }

                base.MouseLeave(sender, e);
            }

            private void SetHover(bool v)
            {
                Hover = v;
            }

            public override bool MouseMove(VirtualPanel sender, VirtualPanelMouseArgs e)
            {
                bool isOverInteractive = deleteButtonRect.Contains(e.Location) || pathRect.Contains(e.Location);

                if (isOverInteractive)
                {
                    sender.Cursor = Cursors.Hand;
                }
                else
                {
                    sender.Cursor = Cursors.Default;
                }

                bool newPathHover = pathRect.Contains(e.Location);
                if (isPathHover != newPathHover)
                {
                    isPathHover = newPathHover;
                    sender.Invalidate();
                    return true;
                }

                bool shouldHover = e.Rect.Contains(e.Location);
                if (Hover != shouldHover)
                {
                    SetHover(shouldHover);
                    sender.Invalidate();
                    return true;
                }

                return base.MouseMove(sender, e);
            }
        }
    }
}